package com.zhou.es.util;

import com.zhou.es.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 解析网页
 * @author zhouyongjun
 * @Description:
 * @date 2021/3/17 21:18
 */
public class HtmlParseUtil {
    public static void main(String[] args) throws IOException {
     /*   //获取请求 URL
        String url = "https://search.jd.com/Search?keyword=java";
        //解析网页,(返回结果Doocument就是浏览器Documnet对象
        Document document = Jsoup.parse(new URL(url), 30000);
        //所有JS中的方法都可以用
        Element element = document.getElementById("J_goodsList");
        System.out.println(element);
        Elements elements = element.getElementsByTag("li");
        for (Element el : elements) {
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
//            String img = el.getElementsByTag("img").eq(0).attr("src");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
            System.out.println("========================");
            System.out.println("img:"+img);
            System.out.println("p-price:"+price);
            System.out.println("p-name:"+title);
        }*/
        parseJD("心理学").forEach(System.out::println);
    }

    /**
     * 解析京东搜索结果
     * @param keywords
     * @return
     * @throws IOException
     */
    public static List<Content> parseJD(String keywords) throws IOException {
//获取请求 URL
        String url = "https://search.jd.com/Search?keyword="+keywords;
        //解析网页,(返回结果Doocument就是浏览器Documnet对象
        Document document = Jsoup.parse(new URL(url), 30000);
        //所有JS中的方法都可以用
        Element element = document.getElementById("J_goodsList");
//        System.out.println(element);
        Elements elements = element.getElementsByTag("li");
        List<Content> goodList = new ArrayList<>();
        for (Element el : elements) {
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
            goodList.add(new Content(title,img,price));
        }
        return goodList;
    }
}
